<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>async函数的语法</title>
</head>
<body>
    <h1>async函数的语法</h1>

    <script>
        // 返回Promise对象
        async function f() {
            return 'hello world';
        }
        f().then(v => console.log(v));

        // await命令
        async function getJson() {
            try {
                const response = await fetch('https://api.example.com/data');
                const json = await response.json();
                return json;
            } catch (error) {
                console.log('Error:', error);
            }
        }

        // 错误处理
        async function errorHandling() {
            try {
                await Promise.reject('出错了');
            } catch (e) {
                console.log(e);
            }
            return await Promise.resolve('成功了');
        }

        // 多个await命令
        async function multipleAwait() {
            try {
                const [foo, bar] = await Promise.all([
                    getFoo(),
                    getBar()
                ]);
            } catch (err) {
                console.error(err);
            }
        }

        // 模拟异步操作
        function getFoo() {
            return new Promise(resolve => setTimeout(() => resolve('foo'), 1000));
        }

        function getBar() {
            return new Promise(resolve => setTimeout(() => resolve('bar'), 500));
        }

        // await命令只能用在async函数中
        // 错误示例：
        // function wrong() {
        //     await Promise.resolve(123); // SyntaxError
        // }

        // 正确示例：
        async function correct() {
            await Promise.resolve(123);
        }
    </script>
</body>
</html> 